<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>stomp-js-websocket</title>
</head>

<body>

    <button type="button" onclick="send()">send message</button>
    <script src="stomp.js"></script>
    <script>
        // 初始化 ws 对象
        var ws = new WebSocket('ws://localhost:15674/ws');

        // 获得Stomp client对象
        var client = Stomp.over(ws);

        // 指定适当的心跳参数保持长时间稳定连接
        client.heartbeat.outgoing = 10000;
        client.heartbeat.incoming = 10000;
    
        // 定义连接成功回调函数
        var on_connect = function (x) {
            //订阅名为default的queue的消息
            client.subscribe("/queue/default", function (data) {
                var msg = data.body;
               console.log("收到数据：" + msg);
               data.ack();
            },{ack:'client'});
            //订阅名为q2的queue的消息,由客户端确认已经收到消息
            client.subscribe("/queue/q2",function(data){
                console.log("q2队列的消息:",data.body);
                data.ack();
            },{ack:'client'});
        };

        // 定义错误时回调函数
        var on_error = function () {
            console.log('error');
        };

        // 连接RabbitMQ
        client.connect('guest', 'guest', on_connect, on_error, '/');

        //向名为debugExchange的exchange中发送消息 ，并指定routingKey 
        function send(){
            //将消息的发送放在一个事务内
            var tx=client.begin();
            client.send("/exchange/debugExchange/debug",{content_Type:"application/json",transaction:tx.id},"hello!!!!!");
            //.....一系列的异步操作,tx.abort()->终止事务
            tx.commit();//提交消息
        }

        //程序退出时候，断开连接
        //client.disconnect();
    </script>
</body>

</html>